"""Logger system configuration - based on Loguru."""

import sys
from pathlib import Path

from loguru import logger


def setup_logger(
        level: str = "INFO",
        log_dir: Path | None = None,
        rotation: str = "10 MB",
        retention: str = "7 days",
        format_string: str | None = None,
) -> None:
    """Configures the Loguru logging system.

    Args:
        level: The minimum logging level (e.g., TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL).
        log_dir: The directory where log files will be stored. If None, a default directory is used.
        rotation: The condition for log file rotation (e.g., "500 MB", "12:00", "1 week").
        retention: The duration for which log files will be retained (e.g., "10 days", "1 month").
        format_string: A custom format string for log messages. If None, a default format is used.
    """
    # 移除默认handler
    logger.remove()

    # 日志格式
    if format_string is None:
        format_string = (
            "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
            "<level>{message}</level>"
        )

    # 控制台处理器 (彩色输出)
    logger.add(
        sys.stdout,
        level=level,
        format=format_string,
        colorize=True,
        backtrace=True,
        diagnose=True,
    )

    # 文件处理器
    if log_dir is None:
        log_dir = Path.home() / ".swiftshadow" / "logs"

    log_dir.mkdir(parents=True, exist_ok=True)

    # 主日志文件 (INFO及以上)
    logger.add(
        log_dir / "swiftshadow.log",
        level="INFO",
        format=format_string,
        rotation=rotation,
        retention=retention,
        compression="zip",
        encoding="utf-8",
        backtrace=True,
        diagnose=True,
    )

    # 错误日志文件 (ERROR及以上)
    logger.add(
        log_dir / "errors.log",
        level="ERROR",
        format=format_string,
        rotation=rotation,
        retention=retention,
        compression="zip",
        encoding="utf-8",
        backtrace=True,
        diagnose=True,
    )

    # 调试日志文件 (仅在测试时启用)
    import os
    if os.environ.get("SWIFTSHADOW_TEST_DEBUG") == "true":
        logger.add(
            log_dir / "test_debug.log",
            level="DEBUG",
            format=format_string,
            rotation=rotation,
            retention=retention,
            compression="zip",
            encoding="utf-8",
            backtrace=True,
            diagnose=True,
        )

    logger.info(f"日志系统已初始化 - 级别: {level}, 目录: {log_dir}")


def get_logger(name: str = None):
    """Retrieves a Loguru logger instance.

    This function is provided for compatibility with older logging patterns;
    Loguru typically manages a global singleton logger instance.

    Args:
        name: The name of the logger (Loguru automatically infers this from the call stack).

    Returns:
        The Loguru logger instance.
    """
    return logger
